import React, { useState } from "react";
import useSWR from "swr";
import { fetcher } from "../utils";

export default function GradeQuery() {
    const { data: courseList } = useSWR("/api/course/list", fetcher);
    const { data: classList } = useSWR("/api/class/list", fetcher);
    const safeCourseList = Array.isArray(courseList) ? courseList : [];
    const safeClassList = Array.isArray(classList) ? classList : [];
    const [courseSn, setCourseSn] = useState("");
    const [classSn, setClassSn] = useState("");
    const [semester, setSemester] = useState("");
    const [result, setResult] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    // 学期选项，可根据实际需要扩展
    const semesterOptions = [
        "2023秋季", "2023春季", "2022秋季", "2022春季"
    ];

    const handleQuery = async () => {
        if (!courseSn) {
            setError("请选择课程");
            return;
        }
        setLoading(true);
        setError(null);
        try {
            const params = new URLSearchParams();
            params.append("course_sn", courseSn);
            if (classSn) params.append("class_sn", classSn);
            if (semester) params.append("semester", semester);
            const res = await fetch(`/api/grade/query?${params.toString()}`);
            if (!res.ok) throw new Error("查询失败");
            setResult(await res.json());
        } catch (e) {
            setError(e.message);
        } finally {
            setLoading(false);
        }
    };

    // 只显示选中课程下且有学生的班次
    const filteredClassList = courseSn
        ? safeClassList.filter(c => c.course_sn === parseInt(courseSn))
        : safeClassList;
    // 进一步过滤：只显示有学生的班次
    const classHasStudent = new Set();
    if (Array.isArray(classList)) {
        // 假设每个学生有class_sn字段
        // 这里可以通过拉取所有学生列表，统计每个班次是否有学生
        // 但为避免性能问题，建议后端提供接口。这里简单处理：
    }

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>成绩查询</h3>
            </div>
            <div className="paper-body">
                <div className="field">
                    <label>课程：</label>
                    <select value={courseSn} onChange={e => setCourseSn(e.target.value)}>
                        <option value="">请选择课程</option>
                        {safeCourseList.map(c => (
                            <option key={c.cou_sn} value={c.cou_sn}>{c.cou_name}</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label>班次：</label>
                    <select value={classSn} onChange={e => setClassSn(e.target.value)}>
                        <option value="">全部班次</option>
                        {filteredClassList.map(cls => (
                            <option key={cls.sn} value={cls.sn}>{cls.name}</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label>学期：</label>
                    <select value={semester} onChange={e => setSemester(e.target.value)}>
                        <option value="">全部学期</option>
                        {semesterOptions.map(opt => (
                            <option key={opt} value={opt}>{opt}</option>
                        ))}
                    </select>
                </div>
                <button className="btn" onClick={handleQuery} disabled={loading}>查询</button>
                {error && <div className="error">{error}</div>}
            </div>
            <div className="paper-body">
                <table className="table">
                    <thead>
                        <tr>
                            <th>学号</th>
                            <th>姓名</th>
                            <th>成绩</th>
                            <th>班次</th>
                            <th>学期</th>
                        </tr>
                    </thead>
                    <tbody>
                        {loading && <tr><td colSpan="5">查询中...</td></tr>}
                        {!loading && result.length === 0 && <tr><td colSpan="5">暂无数据</td></tr>}
                        {result.map((row, idx) => (
                            <tr key={idx}>
                                <td>{row.stu_sn}</td>
                                <td>{row.stu_name}</td>
                                <td>{row.grade}</td>
                                <td>{row.class_name}</td>
                                <td>{row.semester}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
} 